package com.code2roc.fastboot.framework.extra.validatecode;

import com.code2roc.fastboot.framework.auth.AnonymousAccess;
import com.code2roc.fastboot.framework.model.Result;
import com.code2roc.fastboot.framework.model.BaseController;
import com.code2roc.fastboot.framework.util.ConvertOp;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/frame/validatecode")
@AnonymousAccess
public class ValidateCodeController extends BaseController {
    @Autowired
    private ValidateCodeUtil validateCodeUtil;

    @PostMapping("/getValidateCode")
    @ResponseBody
    @AnonymousAccess
    public Object getValidateCode(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String key = ConvertOp.convert2String(params.get("key"));
        String base64Image = validateCodeUtil.getBase64ValidateImage(key);
        result.add("obj", "data:image/gif;base64," + base64Image);
        return result;
    }

    @PostMapping("/checkValidateCode")
    @ResponseBody
    @AnonymousAccess
    public Object checkValidateCode(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String key = ConvertOp.convert2String(params.get("key"));
        String validteCode = ConvertOp.convert2String(params.get("validteCode"));
        String msg = validateCodeUtil.checkValidate(key, validteCode);
        if (!StringUtil.isEmpty(msg)) {
            return Result.errorResult().setMsg(msg);
        }
        return result;
    }
}
